# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from google.appengine.ext import db


class UniqueScope(db.Model):
    """Defines a uniqueness scope in our store."""

    name = db.StringProperty()


class UniqueKey(db.Model):
    """Defines a unique key value inside a scope."""

    value = db.StringProperty()


def add_key(scope, value):
    """Tries to add the given key to the scope.

    Returns True if the key gets successfully added or False if there was an
    existing key in the given scope.

    """
    # We should probably add scopes in a setup utility
    scope_entity = UniqueScope.get_or_insert(scope, name=scope)

    def txn():
        entity = UniqueKey.get_by_key_name(value, parent=scope_entity)
        if entity is None:
            entity = UniqueKey(key_name=value, value=value,
                               parent=scope_entity)
            entity.put()
            return True
        else:
            return False
    return db.run_in_transaction(txn)


def remove_key(scope, value):
    """Tries to remove the given unique key from the scope."""
    scope_key = db.Key.from_path('UniqueScope', scope)
    value_key = db.Key.from_path('UniqueKey', value, parent=scope_key)
    db.delete(value_key)


def replace_key(scope, old, new):
    """Tries to replace a unique key in a given scope.

    This method is useful if you consider we need to first make sure the new
    key value got correctly added before removing the old one.

    Returns True if the new key value gets successfully added or False if it
    was not unique. In case of False, the old value will not be removed.

    """
    if add_key(scope, new):
        remove_key(scope, old)
        return True
    else:
        return False
